<?php
/**
 *RechargeServices
 * @author tan bing
 * @date 2021-10-12 14:41
 */


namespace Modules\Recharge\Services\Api;


use App\Enums\ModuleEnum;
use App\Extend\Random;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Recharge\Entities\RechargeOrder;
use Modules\Recharge\Entities\RechargeOrderPlan;
use Modules\Recharge\Entities\RechargeSetting;
use Modules\Recharge\Enums\SettingEnum;
use Modules\Recharge\Repositories\Contracts\RechargeOrderInterface;
use Modules\Recharge\Repositories\Contracts\RechargePlanInterface;
use Illuminate\Support\Facades\URL;
use Modules\Recharge\Validate\Api\RechargeValidate;
use Modules\User\Entities\UserCapitalLog;
use Modules\User\Repositories\Contracts\UserInterface;
use Nwidart\Modules\Facades\Module;

class RechargeServices extends BaseService
{
    /**
     * @var Request
     * @author tan bing
     */
    private Request $request;

    /**
     * @var RechargeValidate
     * @author tan bing
     */
    private RechargeValidate $validate;

    private UserInterface $userInterface;

    /**
     * @var RechargePlanInterface
     * @author tan bing
     */
    private RechargePlanInterface $rechargePlanInterface;

    /**
     * @var RechargeOrderInterface
     * @author tan bing
     */
    private RechargeOrderInterface $rechargeOrderInterface;

    /**
     * RechargeServices constructor.
     *
     * @param Request $request
     * @param RechargePlanInterface $rechargePlanInterface
     * @param RechargeOrderInterface $rechargeOrderInterface
     * @param RechargeValidate $rechargeValidate
     * @param UserInterface $userInterface
     * @author tan bing
     * @date 2021-10-12 15:10
     */
    public function __construct(
        Request $request,
        RechargePlanInterface $rechargePlanInterface,
        RechargeOrderInterface $rechargeOrderInterface,
        RechargeValidate $rechargeValidate,
        UserInterface $userInterface
    )
    {
        $this->request = $request;
        $this->validate = $rechargeValidate;
        $this->userInterface = $userInterface;
        $this->rechargePlanInterface = $rechargePlanInterface;
        $this->rechargeOrderInterface = $rechargeOrderInterface;
    }

    /**
     * @return mixed
     * @author tan bing
     * @date 2021-10-29 15:32
     */
    public function user()
    {
        $userId = $this->request->attributes->get('userId');
        return User::find($userId);
    }

    /**
     * @return array|mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @author tan bing
     * @date 2021-10-12 14:47
     */
    public function getRechargeConfig()
    {
        $result = RechargeSetting::where('key', SettingEnum::RECHARGE)->first();
        if(!$result) $result = RechargeSetting::getDefaultData();
        else {
            $result = $result->values;
        }
        !empty($result['bg_image']) && $result['thumb_bg_image'] = URL::asset('') . $result['bg_image'];
        !empty($result['ad_image']) && $result['thumb_ad_image'] = URL::asset('') . $result['ad_image'];
        !empty($result['recharge_describe_icon']) && $result['thumb_recharge_describe_icon'] = URL::asset('') . $result['recharge_describe_icon'];

        return $result;
    }

    /**
     * @return array
     * @author tan bing
     * @date 2021-10-12 14:49
     */
    public function getRechargePlan()
    {
        $param = $this->request->input();
        $query = $this->rechargePlanInterface->getPageData($param, $this->perPage());
        $data = $query->items();
        $count = $query->total();
        return compact('count', 'data');
    }

    /**
     * @return array
     * @author tan bing
     * @date 2021-10-12 16:36
     */
    public function getRechargeOrder()
    {
        $param = $this->request->input();
        $userId = $this->request->attributes->get('userId');
        $date = !empty($param['date']) ? $param['date'] : date('Y-m');
        $dateTime = date('Y-m-1 00:00:00', strtotime($date)) . ' - ' . date('Y-m-t 00:00:00', strtotime($date));
        $param['user_id'] = $userId;
        $param['created_at'] = $dateTime;
        $param['type'] = 1;
        $list = $this->rechargeOrderInterface->get($param);
        $list = UserCapitalLog::addWhere($param)->get();
        return compact('date', 'list');
    }

    public function rechargeDetail()
    {
        $id = $this->request->post('id');
        return UserCapitalLog::find($id);
    }

    /**
     * @return mixed
     * @throws \Throwable
     * @author tan bing
     * @date 2021-10-15 9:39
     */
    public function rechargeOrder()
    {
        if(!$this->validate->check($this->request->post()))
            throw new \Exception($this->validate->getError());

        $amount = $this->request->post('amount', 0);
        $planId = $this->request->post('plan_id', 0);
        $userId = $this->request->attributes->get('userId');

        if(!$amount && !$planId)
            throw new \Exception('请输入或选择充值金额');

        try {
            $giftAmount    = 0;
            $giftIntegral  = 0;
            $giftCouponIds = '';
            $rechargeType  = 10;
            $planName = '自定义充值金额';
            if($planId) {
                $plan = $this->rechargePlanInterface->findById($planId);
                if (!$plan)
                    throw new \Exception('Request Param Error.');
                $rechargeType = 20;
                $amount         = $plan->money;
                $giftAmount     = $plan->gift_money;
                $giftIntegral   = $plan->gift_integral;
                $giftCouponIds  = $plan->gift_coupons;
                $planName = $plan->plan_name;
            }
            $data = [
                'user_id'       => $userId,
                'plan_id'       => $planId,
                'amount'        => $amount,
                'gift_amount'   => $giftAmount,
                'gift_integral' => $giftIntegral,
                'gift_coupons'  => $giftCouponIds,
                'recharge_type' => $rechargeType,
                'plan_name'     => $planName,
                'order_sn'      => getSn('R', $userId),
            ];
            DB::beginTransaction();
            $rechargeOrder = $this->rechargeOrderInterface->addRechargeOrder($data);
            $data['order_id'] = $rechargeOrder->id;
            $rechargeOrderPlan = $this->rechargeOrderInterface->addRechargeOrderPlan($data);
            $rechargeOrder->recharge_order_plan = $rechargeOrderPlan;
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }

        return $rechargeOrder;
    }
}